package top.tagao.m03_beHavioralPatterns.b_08_observer.publisher;

import top.tagao.m03_beHavioralPatterns.b_08_observer.listeners.EventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发布者（Publisher）
 * @author Viktor_Liu
 * @Date 2022/8/14 11:26
 */
public class EventManager {
    Map<String, List<EventListener>> listeners = new HashMap<>();

    public EventManager(String... operations) {
        for (String operation : operations) {
            this.listeners.put(operation, new ArrayList<>());
        }
    }
    // 订阅
    public void subscribe(String eventType, EventListener listener) {
        List<EventListener> users = listeners.get(eventType);
        users.add(listener);
    }
    // 取消订阅
    public void unsubscribe(String eventType, EventListener listener) {
        List<EventListener> users = listeners.get(eventType);
        users.remove(listener);
    }
    // 通知
    public void notify(String eventType, String file) {
        //获取订阅了 eventType的 订阅者列表，循环订阅列表，向每一个订阅者发送通知
        List<EventListener> users = listeners.get(eventType);
        for (EventListener listener : users) {
            listener.update(eventType, file);
        }
    }
}
